package server

import (
	"errors"
	"fitness/common/models/mysql"
	fitness "fitness/common/proto"
	"fmt"
)

func AddReservation(in *fitness.AddReservationReq) (*fitness.AddReservationResp, error) {
	r := &mysql.Reservation{}
	f := &mysql.Fitness{}
	findFitness, err := f.FindFitness(in.ClassName)
	if err != nil {
		return nil, err
	}
	if findFitness.ID == 0 {
		return nil, errors.New("没有这个课程")
	}
	err = r.CreateFitness(in.ClassName, in.AddTime, in.Address, in.Teacher, in.Context)
	if err != nil {
		return nil, errors.New("创建失败")
	}
	return &fitness.AddReservationResp{Greet: "创建成功"}, nil
}
func UserLogin(in *fitness.UserLoginReq) (*fitness.UserLoginResp, error) {
	u := &mysql.User{}
	username, err := u.FindUserByUsername(in.Username)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if username.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	if username.Password != in.Password {
		return nil, errors.New("密码错误")
	}
	return &fitness.UserLoginResp{Greet: int64(username.ID)}, nil
}
func FitnessList(in *fitness.FitnessListReq) (*fitness.FitnessListResp, error) {
	f := &mysql.Fitness{}

	fit, err := f.FindFitnessById(in.FitnessId)
	if err != nil {
		return nil, errors.New("查询失败")
	}

	var List []*fitness.FitnessList
	for _, i2 := range fit {
		List = append(List, &fitness.FitnessList{
			ClassName: i2.ClassName,
			Price:     float32(i2.Price),
		})
	}

	return &fitness.FitnessListResp{List: List}, nil
}
func ReservationList(in *fitness.ReservationListReq) (*fitness.ReservationListResp, error) {
	r := &mysql.Reservation{}

	fit, err := r.FindReservationById(in.UserId)
	if err != nil {
		return nil, errors.New("查询失败")
	}

	var List []*fitness.ReservationList
	for _, i2 := range fit {
		List = append(List, &fitness.ReservationList{
			ClassName: i2.ClassName,
			AddTime:   i2.AddTime,
			Status:    i2.Status,
			Address:   i2.Address,
			Teacher:   i2.Teacher,
		})

	}
	fmt.Println(List)
	return &fitness.ReservationListResp{List: List}, nil

}

func FindUserReservation(in *fitness.FindUserReservationReq) (*fitness.FindUserReservationResp, error) {
	u := &mysql.User{}
	r := &mysql.Reservation{}
	username, err := u.FindUserByUsername(in.Username)
	if err != nil {
		return nil, err
	}
	id, err := r.FindReservationById(int64(username.ID))
	if err != nil {
		return nil, err
	}
	var lists []*fitness.FindUserReservation
	for _, m := range id {
		lists = append(lists, &fitness.FindUserReservation{
			ClassName: m.ClassName,
			AddTime:   m.AddTime,
			Status:    m.Status,
			Address:   m.Address,
			Teacher:   m.Teacher,
		})
	}
	return &fitness.FindUserReservationResp{List: lists}, nil

}
